//
//  LoginViewController.m
//  EEEEat
//
//  Created by mac on 15/12/26.
//  Copyright © 2015年 mac. All rights reserved.
//

#import "LoginViewController.h"
#import "MyTools.h"
#import "LCTabBarController.h"
#import "AFNetworking.h"
#import "UIView+Toast.h"
#import "EditorViewController.h"
#import "RegisterViewController.h"
#import "ForgetViewController.h"
#import "JPUSHService.h"


@interface LoginViewController ()
@end

@implementation LoginViewController
{
    UITextField *   _nametextFied;
    UITextField *   _codetextFied;
    UIButton *      _lookBtn;
    int _count;
}
- (void)viewDidLoad {
    //self.view.backgroundColor =UIColorFromRGB(MYGreen);
    //    self.view.backgroundColor =[UIColor colorWithPatternImage:[UIImage imageNamed:@"denglu_bg.png"]];
    
    UIImageView *imageview = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
    imageview.image = [UIImage imageNamed:@"denglu_bg.png"];
    [self.view addSubview:imageview];
    self.view.backgroundColor = [UIColor whiteColor];
    [super viewDidLoad];
    [self creatTextField];
    [self loginbutton];
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    self.navigationController.interactivePopGestureRecognizer.delegate =(id)self;
    // Do any additional setup after loading the view.
}

- (void)loginbutton{
    UIImageView *image = [[UIImageView alloc]initWithFrame:CGRectMake(WIDTH/2-50*MYWIDTH, 90*MYHEIGHT, 100*MYWIDTH, 100*MYWIDTH)];
    image.layer.masksToBounds = YES;
    image.layer.cornerRadius = 50*MYWIDTH;
    image.image = [UIImage imageNamed:@"Icon-120"];
    [self.view addSubview:image];
    //登录
    UIButton *loginbut = [[UIButton alloc]initWithFrame:CGRectMake(WIDTH/2-(WIDTH/2 - 20)*MYWIDTH+15, 390*MYHEIGHT, (WIDTH - 40)*MYWIDTH-30, 40*MYWIDTH)];
    [loginbut setBackgroundColor:UIColorFromRGB(MYColor)];
    [loginbut addTarget:self action:@selector(loginbut:) forControlEvents:UIControlEventTouchUpInside];
    [loginbut setTitle:@"登录" forState:UIControlStateNormal];
    loginbut.titleLabel.font = [UIFont fontWithName:@"Heiti SC" size:15];
    loginbut.layer.masksToBounds = YES;
    loginbut.layer.cornerRadius = 5;
    [self.view addSubview:loginbut];
    //忘记密码
    UIButton *forgetcodebut = [[UIButton alloc]initWithFrame:CGRectMake(WIDTH - 80, _codetextFied.frame.origin.y+50, 80, 20)];
    forgetcodebut.backgroundColor =[UIColor clearColor];
    [forgetcodebut setTitle:@"忘记密码？" forState:UIControlStateNormal];
    [forgetcodebut setTitleColor:UIColorFromRGB(MYColor) forState:UIControlStateNormal];
    forgetcodebut.titleLabel.font = [UIFont systemFontOfSize:13];
    [forgetcodebut addTarget:self action:@selector(forgetcode:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:forgetcodebut];
    
    UIButton *registerBtn = [[UIButton alloc]initWithFrame:CGRectMake(10, _codetextFied.frame.origin.y+50, 80, 20)];
    registerBtn.backgroundColor = [UIColor clearColor];
    [registerBtn setTitle:@"注册" forState:UIControlStateNormal];
    [registerBtn setTitleColor:UIColorFromRGB(MYColor) forState:UIControlStateNormal];
    registerBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    [registerBtn addTarget:self action:@selector(registerBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:registerBtn];
}
-(void)registerBtnClick:(UIButton *)btn{
    
    RegisterViewController *registerVC = [[RegisterViewController alloc]init];
    [self presentViewController:registerVC animated:YES completion:nil];
}

//登录点击事件
- (void)loginbut:(UIButton *)nut{
    UITextField *nametextFied = (id)[self.view viewWithTag:10];
    UITextField *codetextFied = (id)[self.view viewWithTag:11];
    
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    
    if ([nametextFied.text isEqualToString:@""]) {
        //  [self.view makeToast:@"用户名不能为空" duration:2 position:CSToastPositionCenter];
        alert.title = @"手机号不能为空!";
        alert.tag = 1;
        [alert show];
    }else{
        if ([codetextFied.text isEqualToString:@""] ) {
            alert.title = @"密码不能为空!";
            alert.tag = 2;
            [alert show];
        }else{
            NSString * username = _nametextFied.text;
            NSString * password = _codetextFied.text;
            NSDictionary *dic = @{@"mobile":_nametextFied.text,
                                  @"password":_codetextFied.text};
            
            AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
            manager.responseSerializer = [AFHTTPResponseSerializer serializer];
            manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
            manager.requestSerializer = [AFHTTPRequestSerializer serializer];
            // [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            
            [manager POST:LOGIN_URL parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
                NSDictionary *dic1 = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
                NSString * str = [NSString stringWithFormat:@"%@",[dic1 objectForKey:@"status"]];
                if ([str isEqualToString:@"1"]) {
                    
                    NSDictionary *dic2 = [dic1 objectForKey:@"data"];
                    NSDictionary *levelDic = [dic2 objectForKey:@"level"];
                    NSLog(@"levelDic  %@",levelDic);
                    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
                    //登录成功后把用户名和密码存储到UserDefault
                    [user setObject:username forKey:@"mobile"];
                    [user setObject:password forKey:@"password"];
                    [user setObject:[dic2 objectForKey:@"nickname"] forKey:@"nickname"];
                    [user setObject:[dic2 objectForKey:@"avatar256"] forKey:@"imageurl"];
                    [user setObject:[dic2 objectForKey:@"user_token"] forKey:@"token"];
                    [user setObject:[dic2 objectForKey:@"sex"] forKey:@"sex"];
                    [user setObject:[dic2 objectForKey:@"uid"] forKey:@"uid"];
                    [user setObject:[dic2 objectForKey:@"agents_level"] forKey:@"agents_level"];
                    [user setObject:[dic2 objectForKey:@"share_count"] forKey:@"share_count"];

                    
                    [user synchronize];
                    NSLog(@"user %@",user);
                    NSLog(@"user_token %@",[user objectForKey:@"user_token"]);
                    //   [MBProgressHUD hideHUDForView:self.view animated:YES];
                    [self joinJPush:[NSString stringWithFormat:@"%@",[dic2 objectForKey:@"uid"]]];
                    [self.view makeToast:@"登录成功" duration:0.5 position:CSToastPositionCenter];
                    NSLog(@"%@",dic1[@"info"]);
                    LCTabBarController *LCTabVC = [[LCTabBarController alloc]init];
                    [self presentViewController:LCTabVC animated:YES completion:nil];
                    
                }else{
                    //   [MBProgressHUD hideHUDForView:self.view animated:YES];
                    [self.view makeToast:dic1[@"info"] duration:0.5 position:CSToastPositionCenter];
                    NSLog(@"%@",dic1[@"info"]);
                }
            }
                  failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                      //   [MBProgressHUD hideHUDForView:self.view animated:YES];
                      [self.view makeToast:@"登录失败!" duration:1.0 position:CSToastPositionCenter];
                      NSLog(@"%@",error.description);
                      
                  }];
        }
    }
}
#pragma mark 用户+标签、别名
-(void)joinJPush:(NSString *)alias{
    //    NSLog(@"123");
    NSLog(@"%@",alias);
    //[JPUSHService setTags:tag alias:@"yong" callbackSelector:@selector(tagsAliasCallback:tags:alias:) object:];
    
    //[JPUSHService setTags:tag aliasInbackground:@"yong"];
    
    [JPUSHService setTags:nil alias:alias fetchCompletionHandle:^(int iResCode, NSSet *iTags, NSString *iAlias) {
        NSLog(@"rescode: %d, \ntags: %@, \nalias: %@\n", iResCode, iTags , iAlias);
    }];
}
//忘记密码点击事件
-(void)forgetcode:(UIButton *)forgetcodebut{
    NSLog(@"忘记密码");
    ForgetViewController *forgetVC = [[ForgetViewController alloc]init];
    [self presentViewController:forgetVC animated:YES completion:nil];
    //    LCTabBarController * vc =[[LCTabBarController alloc]init];
    //    [self presentViewController:vc animated:YES completion:nil];
}
#pragma mark -创建UITextField
-(void)creatTextField
{
    
    
    _nametextFied = [[UITextField alloc]initWithFrame:CGRectMake( 55, 200*MYHEIGHT, WIDTH - 15, 55)];
    _codetextFied = [[UITextField alloc]initWithFrame:CGRectMake( 55, 270*MYHEIGHT, WIDTH - 15, 55)];
    _codetextFied.secureTextEntry = YES;//设置密文显示效果
    _lookBtn = [[UIButton alloc]initWithFrame:CGRectMake(WIDTH - 75, 270 *MYHEIGHT, 40, 40)];
    [_lookBtn setImage:[UIImage imageNamed:@"眼睛"] forState:UIControlStateNormal];
    [_lookBtn addTarget:self action:@selector(BtnClick:) forControlEvents:UIControlEventTouchUpInside];
    _count = 1;
    
    UIImageView *phoneImage = [[UIImageView alloc]init];
    phoneImage.image =[UIImage imageNamed:@"denglu"];
    phoneImage.frame = CGRectMake(20, _nametextFied.frame.origin.y+10, 25, 25);
    [self.view addSubview:phoneImage];
    
    UIImageView *passwordImage = [[UIImageView alloc]init];
    passwordImage.image =[UIImage imageNamed:@"密码"];
    passwordImage.frame = CGRectMake(20, _codetextFied.frame.origin.y+10, 25, 25);
    [self.view addSubview:passwordImage];
    
    _nametextFied.tag = 10;
    _codetextFied.tag = 11;
    _nametextFied.borderStyle = UITextBorderStyleNone;
    _codetextFied.borderStyle = UITextBorderStyleNone;
    _nametextFied.font =[UIFont systemFontOfSize:15];
    _codetextFied.font =[UIFont systemFontOfSize:15];
    _nametextFied.placeholder = @"请输入手机号";
    _nametextFied.keyboardType = UIKeyboardTypeNumberPad;
    _codetextFied.placeholder = @"请输入密码";
    _codetextFied.secureTextEntry = YES;
    
    [self.view addSubview:_nametextFied];
    [self.view addSubview:_codetextFied];
    [self.view addSubview:_lookBtn];
    
    UIView *lineview = [[UIView alloc]initWithFrame:CGRectMake(WIDTH / 15, _nametextFied.frame.origin.y+40, WIDTH - WIDTH / 7.5, 1)];
    lineview.backgroundColor = UIColorFromRGB(MYGray);
    [self.view addSubview:lineview];
    
    UIView *lineview1 = [[UIView alloc]initWithFrame:CGRectMake(WIDTH / 15, _codetextFied.frame.origin.y+40, WIDTH - WIDTH / 7.5, 0.5)];
    lineview1.backgroundColor = UIColorFromRGB(MYGray);
    [self.view addSubview:lineview1];
    
    //手势
    UITapGestureRecognizer *tgr = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tgrClick:)];
    
    [self.view addGestureRecognizer:tgr];
    
}
-(void)BtnClick:(UIButton *)btn{
    _count ++;
    if (_count % 2 == 0) {
        _codetextFied.secureTextEntry = NO;
    }if (_count % 2 == 1) {
        _codetextFied.secureTextEntry = YES;
    }
}
- (void)tgrClick:(UITapGestureRecognizer *)tgr{
    
    UITextField *nametextField = (id)[self.view viewWithTag:10];
    //放弃第一响应
    [nametextField resignFirstResponder];
    
    UITextField *codetextField = (id)[self.view viewWithTag:11];
    [codetextField resignFirstResponder];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.translucent = YES;
    self.navigationController.navigationBar.hidden = NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
